﻿using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using Microsoft.AspNetCore.Identity;
using StsServer.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace StsServer.Services
{
    //public class CustomResourceOwnerPasswordValidator
    //{
    //}
    public class CustomResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        private readonly IUserStore<ApplicationUser> _userRepository;
        private readonly UserManager<ApplicationUser> _userManager;

        public CustomResourceOwnerPasswordValidator(UserManager<ApplicationUser> userManager,
            IUserStore<ApplicationUser> userRepository)
        {
            _userManager = userManager;
            _userRepository = userRepository;
        }

        public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            //if (_userRepository.ValidateCredentials(context.UserName, context.Password))
            //{
            //    var user = _userRepository.FindByUsername(context.UserName);
            //    context.Result = new GrantValidationResult(user.SubjectId, OidcConstants.AuthenticationMethods.Password);
            //}
            //return Task.FromResult(0);

            // 这里让我们有机会来 改变 context.Result：
            // 同时还有个context.Request: ValidatedTokenRequest
            // context.Request是客户端传过来的内容，我们可以认为是我们
            // 本方法中展开工作的 Recipes
            var request = context.Request;

            var raw = request.Raw;
            var subject = request.Subject;
            var client = request.Client;
            var claims = request.ClientClaims;
            var scopes = request.Scopes;
            var vscopes = request.ValidatedScopes;

            var user = _userManager.FindByNameAsync(context.UserName);

            var response = new Dictionary<string, object>
            {
                { "string_value", "some_string" },
                { "int_value", 42 },
                { "dto",   "sss"}//CustomResponseDto.Create
            };

            if (context.UserName == context.UserName) // 让这里始终成立
            {
                context.Result = new GrantValidationResult(context.UserName,
                    "password",
                    claims: GetUserClaims(),
                    customResponse: response);
            }
            else
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid_credential", response);
            }

            return Task.CompletedTask;


            ////根据context.UserName和context.Password与数据库的数据做校验，判断是否合法 
            //if (context.UserName == "wjk" && context.Password == "123")
            //{
            //    context.Result = new GrantValidationResult(
            //     subject: context.UserName,
            //     authenticationMethod: "custom",
            //     claims: GetUserClaims());
            //}
            //else
            //{
            //    //验证失败
            //    context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid custom credential");
            //}
            //return Task.FromResult(0);
        }
        //可以根据需要设置相应的Claim
        private Claim[] GetUserClaims()
        {
            return new Claim[]
            {
               new Claim("UserId", 1.ToString()),
               new Claim(JwtClaimTypes.Name,"wjk"),
               new Claim(JwtClaimTypes.GivenName, "jaycewu"),
               new Claim(JwtClaimTypes.FamilyName, "yyy"),
               new Claim(JwtClaimTypes.Email, "977865769@qq.com"),
               new Claim(JwtClaimTypes.Role,"admin")
            };
        }
    }
}
